<template>
  <div>
    <!--<el-table
      :data="attrGroupVoList"
      row-key="attrGroupId">
      <el-table-column
        prop="attrGroupName"
        label="属性分组">
        <template slot-scope="slot">
          <el-row :gutter="20">
            <el-col :span="6">
              &lt;!&ndash;              <div class="grid-content bg-purple"></div>&ndash;&gt;
              <span v-text="slot.row.attrGroupName"></span>
            </el-col>
            <el-col :span="6">
              <img :src="hostAddress+slot.row.icon" alt="" width="100" v-if="hostAddress">
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="18" :offset="3">
              <el-table :data="slot.row.attrList">
                <el-table-column prop="attrName"></el-table-column>
                <el-table-column prop="icon">
                  <template slot-scope="slot2">
                    <img :src="hostAddress+slot2.row.icon" alt="" width="100" v-if="hostAddress">
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot-scope="slot2">
                    <el-input></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </template>
      </el-table-column>

    </el-table>-->

    <el-radio-group v-model="tabPosition" style="margin-bottom: 30px;">
      <el-radio-button label="top">top</el-radio-button>
      <el-radio-button label="right">right</el-radio-button>
      <el-radio-button label="bottom">bottom</el-radio-button>
      <el-radio-button label="left">left</el-radio-button>
    </el-radio-group>

    <el-tabs :tab-position="tabPosition">

      <el-tab-pane :label="group.attrGroupName" v-for="(group,index) in attrGroupVoList" :key="group.attrGroupId">
        <!--
                <el-radio-group v-model="labelPosition" size="small">
                  <el-radio-button label="left">左对齐</el-radio-button>
                  <el-radio-button label="right">右对齐</el-radio-button>
                  <el-radio-button label="top">顶部对齐</el-radio-button>
                </el-radio-group>

                <div style="margin: 20px;"></div>

                <el-form :label-position="labelPosition" :model="formLabelAlign" label-width="200px" >

                  &lt;!&ndash;
                          {
                            "attrId": 1,
                            "attrName": "屏幕材质类型",
                            "searchType": 1,
                            "icon": "2020/09/22/cfbab919-a6bf-4506-8bf5-09e5a41b4fa7-66293.jpg",
                            "valueSelect": "OLED,AMOLED",
                            "attrType": 1,
                            "enable": 0,
                            "catelogId": 225,
                            "showDesc": 1,
                            "selectMultiple": true
                          }
                  &ndash;&gt;
                  <el-form-item :label="attr.attrName" v-for="(attr,index2) in group.attrList" :key="attr.attrId" size="medium">
                    &lt;!&ndash;            <el-input v-model="formLabelAlign.name"></el-input>&ndash;&gt;

                    <el-select v-model="attr.attrValue" :multiple="attr.selectMultiple" placeholder="请选择">
                      <el-option
                        v-for="(item,index3) in attr.valueSelect.split(',')"
                        :key="index3"
                        :label="item"
                        :value="index3">
                      </el-option>
                    </el-select>
                    <el-tag v-if="attr.selectMultiple">支持多选</el-tag>
                  </el-form-item>

        &lt;!&ndash;          快速展示【是否展示在介绍上；0-否 1-是】&ndash;&gt;

                   <el-form-item label="活动形式">
                    <el-input v-model="formLabelAlign.type"></el-input>
                  </el-form-item>
                </el-form>-->

        <el-table
          :data="group.attrList"
          row-key="attrId"
          stripe
          style="width: 100%">

          <el-table-column
            prop="attrName"
            label="属性名称"
            width="200">
          </el-table-column>

          <el-table-column
            prop="valueSelect"
            label="可选值"
            width="400">
            <template slot-scope="slot">
              <el-select v-model="slot.row.selectedValueIndexArray"
                         @change="filterToPmsAttr(slot.row,index,slot.$index)"
                         :multiple="slot.row.selectMultiple" placeholder="请选择"
                         filterable
                         allow-create>

                <el-option
                  v-for="(item,index3) in slot.row.valueSelect.split(',')"
                  :key="index3"
                  :label="item"
                  :value="index3">
                </el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column
            prop="selectMultiple"
            label="选择模式">
            <template slot-scope="slot">
              <el-tag v-if="slot.row.selectMultiple">支持多选</el-tag>
              <el-tag v-else type="success">单选</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="快速展示">
            <!--            快速展示【是否展示在介绍上；0-否 1-是】这里因为数据库中是tinyInt，所以我将实体类中的类型改为了boolean-->
            <template slot-scope="slot">
              <!--              <el-tooltip :content="slot.row.quickShow?'开启':'关闭'" placement="top">-->
              <el-switch
                v-model="slot.row.quickShow"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="true"
                :inactive-value="false">
              </el-switch>
              <!--              </el-tooltip>-->
            </template>
          </el-table-column>
          <el-table-column label="在本分组中的排序">
            <!--在本分组中的排序-->
            <template slot-scope="slot">
              <el-input-number v-model="slot.row.attrSort" :min="0" size="small"></el-input-number>
            </template>
          </el-table-column>
        </el-table>

      </el-tab-pane>
      <!--      <el-tab-pane label="配置管理">配置管理</el-tab-pane>
            <el-tab-pane label="角色管理">角色管理</el-tab-pane>
            <el-tab-pane label="定时任务补偿">定时任务补偿</el-tab-pane>-->
    </el-tabs>
  </div>
</template>

<script>
import attrGroupApi from '../../../../api/product/attrGroupApi'
import uploadToAiliOss from '../../../../api/uploadToAiliOss'
import baseAttrApi from '../../../../api/product/baseAttrApi'
import spuApi from '../../../../api/product/spuApi'
export default {
  name: 'spuSellAttrValue',
  data () {
    return {
      catelogId: null,
      hostAddress: null,
      attrGroupVoList: [],
      tabPosition: 'left',
      labelPosition: 'right',
      formLabelAlign: {
        name: '',
        region: '',
        type: ''
      }
    }
  },
  methods: {

    async getAttrGroupAndAttrAndAttrValue(spuInfo){
      let p = await spuApi.querySpuInfoAttrValueAndFillIntoAttrGroup(spuInfo);
      this.attrGroupVoList = p.data.list;
      console.log("获取到的attrGroup,attr,attrValue 是",this.attrGroupVoList);
    },

    async getAttrToInput (catelogId) {
      if (catelogId) {
        this.catelogId = catelogId
      }
      let p = await attrGroupApi.getAttrGroupAndItsAttrList(this.catelogId, 1)
      console.log('attrGroupAndItsAttrList', p.data.data)
      this.attrGroupVoList = p.data.data
    },

    filterToPmsAttr (row, groupIndex, attrRowIndex) {

      console.log('行', row, '当前填入的内容是', row.selectedValueIndexArray, `本属性是在第${groupIndex}个组的第${attrRowIndex}个属性`,)

      if (/^[0-9]+$/.test(row.selectedValueIndexArray)) {

        if (typeof row.selectedValueIndexArray === 'string') {
          this.$message({
            message: '抱歉，不能输入纯数字',
            type: 'warning'
          })

          row.selectedValueIndexArray = null

          return
        }

        // if (row.selectedValueIndexArray < row.valueSelect.split(',').length) {
        console.log('用户输入的是数字，且这个数字在valueSelect的索引范围之内，当作鼠标选择')
        return
        // }

      }

      if (typeof row.selectedValueIndexArray === 'object'
        && row.selectedValueIndexArray.length > 0) {

        for (let i = 0; i < row.selectedValueIndexArray.length; i++) {

          let attrId = row.selectedValueIndexArray[i]

          if (/^[0-9]+$/.test(attrId)) {
            console.log(`这个数组中的${i}号元素是数组attrId，不更新`)
            continue
          }

          this.executeUpdateValueSelect(row, groupIndex, attrRowIndex)
        }

        //console.log(typeof row.selectedValueIndexArray, `${row.attrName}填入的是一个多选的数组，直接return`)
        return
      }

      console.log('只能输入一个值的attr选择框，用户输入了自定义内容', row.selectedValueIndexArray)
      this.executeUpdateValueSelect(row, groupIndex, attrRowIndex)

    },

    async executeUpdateValueSelect (row, groupIndex, attrRowIndex) {
      /**
       * 前面两种都没有，说明是用户自己输入的内容
       * */
      let valueSelectArray = row.valueSelect.split(',')

      // 将用户添加的数据放入数组
      valueSelectArray.push(row.selectedValueIndexArray)

      //将数组转为字符串
      let valueSelectString = valueSelectArray.join(',')

      let p = await baseAttrApi.updateValueSelectByAttrId(row.attrId, valueSelectString)

      this.$message({
        message: `属性值：${row.selectedValueIndexArray} 添加成功`,
        type: 'success'
      })

      /* 根据attrID来更新浏览器的属性
       * 只更新局部属性，而不更新全局属性
       * */
      let p2 = await baseAttrApi.getAttrByAttrId(row.attrId)

      /**
       * 根据 groupIndex 和 attrRowIndex 找到要更新的attr的下表，将更新后的数据做替换
       * */
      this.attrGroupVoList[groupIndex].attrList[attrRowIndex] = p2.data.attr

      /**
       * 根据前面的代码逻辑，将新的属性拼接到 valueSelect 的最后面，
       * 此时，更新后的新 value 就是length - 1
       * */
      let newAttrIndex = p2.data.attr.valueSelect.split(',').length - 1

      // 赋值，更新之后恢复用户的选择
      this.attrGroupVoList[groupIndex].attrList[attrRowIndex].selectedValueIndexArray = newAttrIndex
      /*
      这样赋值没用
      row = p2.data.attr

      row.selectedValueIndexArray = p2.data.attrId*/

      /**
       * 还是要更新全局才可以
       * */
      //let p3 = await this.getAttrToInput(this.catelogId)
    },

    /**
     * 父组件调用此方法以获取本组件的数据
     * */
    getAttrGroupVoList () {

      let attrList = new Array()

      /**
       * 遍历属性分组
       * */
      this.attrGroupVoList.forEach((group, index) => {

        if (group.attrList.length > 0) {

          /**
           * 遍历属性分组中的属性
           * */
          let singleGroupAttrList = group.attrList.map((attr,index) => {

            // console.log("属性",attr)

            /**
             * 解构出需要添加的数据
             * 这里的 selectedValueIndexArray 是一个数组，数组的元素是数字，这些数字指向 valueSelect 分成数组之后对应的索引
             * valueSelect 举例 ['30Hz','60Hz','90Hz','144Hz']
             * selectedValueIndexArray 举例 [1,3]
             * 这样 selectedValueIndexArray 代表的 valueSelect 实际值就是 '60Hz','144Hz'
             * */
            let {attrId, selectedValueIndexArray, valueSelect, attrName, quickShow, attrSort, selectMultiple,id} = attr

            // console.log(attr /*, selectedValueIndexArray*/)

            /*if (selectedValueIndexArray == null|| selectedValueIndexArray == undefined) {
              return null;
            }*/

            // 可选择的属性数组
            let selectableValueArray = valueSelect.split(',')

            let attrValue = null

            /**
             * 看这个属性是否支持多选
             * 多选的时候 selectedValueIndexArray 是一个数组
             *
             * */
            if (selectMultiple && selectedValueIndexArray) {

              let selectedValueStrArray = selectedValueIndexArray.map(v => {
                return selectableValueArray[v]
              })

              attrValue = selectedValueStrArray.join(',')

            } else {
              /**
               * 单选的时候 selectedValueIndexArray 不代表数字，只能为数组或者null
               * 不是多选，用户没有选择的话，selectedValueIndexArray 可以为 null
               * 或者为一个数字，数字指向 selectedValueIndexArray 的索引
               * */
              attrValue = selectableValueArray[selectedValueIndexArray]
            }

            return {
              attrId, attrValue, attrName, quickShow, attrSort,id
            }
          })

          let newAttrList = singleGroupAttrList.filter(attr => {
            return attr != null && attr.attrValue && attr.attrValue.length > 0
          })

          /**
           * 合并数组
           * */
          attrList = attrList.concat(newAttrList)
        }
      })

      return attrList
    }

  },

}
</script>

<style scoped>

</style>
